package com.detrum.usbdevice;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.detrum.base.BaseActivity;
import com.detrum.base.BaseFinal;
import com.detrum.base.BaseStatic;
import com.detrum.base.ServiceStatic;
import com.detrum.detrumdata.newd.DFrame;
import com.detrum.detrumdata.newd.DFrameEntity;
import com.detrum.detrumdata.newd.DFrameType;
import com.detrum.detrumdata.newd.DProtocolType;
import com.detrum.detrumdata.service.USBConnetService;
import com.detrum.detrumdata.service.UsbServiceCall1;
import com.detrum.detrumdata.service.UsbServiceCall2;
import com.detrum.usbdevice.customview.ChannelPopupCall;
import com.detrum.usbdevice.customview.ChannelSelectPopup;
import com.detrum.usbdevice.fragment.PreviewFragment;
import com.detrum.usbdevice.fragment.SelectFragment;
import com.detrum.utils.LogUtils;
import com.detrum.utils.MyMethod;
import com.detrum.utils.PermissionCall;
import com.detrum.utils.PermissionRegister;

import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;

public class UAVPreviewActivity extends BaseActivity implements View.OnClickListener,PreviewFragment.OnFragmentInteractionListener,SelectFragment.OnFragmentInteractionListener,PermissionCall{
    private Context context;
    private FragmentManager fragmentManager;
    private FragmentTransaction fragmentTransaction;
    private PreviewFragment previewFragment;
    private SelectFragment selectFragment;
    private boolean itemFragmentShow,videoisStart;
    private PermissionRegister permissionRegister;

    private boolean isLock = true,isStartSearch;
    private ImageView lock_iv;
    private TextView showText;
    private TextView channel_current, capture, video_state, battery_state;
    private ImageView battery_state_iv;
    private CountDownTimer countDownTimer;
    private ChannelSelectPopup channelSelectPopup;
    private String[] strs = new String[9];
    private int currentchannel=11;
    private boolean isResume;

    private USBConnetService usbService;
    private UsbConn usbConn;
    private Intent usbIntent;
    private class UsbConn implements ServiceConnection{

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            usbService = ((USBConnetService.UsbBinder)service).getService();
            usbService.setUsbServiceCall1(new UsbServiceCall1() {
                @Override
                public void connect() {

                }

                @Override
                public void disconnect() {
                    UAVPreviewActivity.this.finish();
                }

                @Override
                public void onVersion(boolean isSuccess) {

                }
            });
            usbService.setUsbServiceCall2(new UsbServiceCall2() {

                @Override
                public void onUndecodeframeget(byte[] bys, int offset, int length) {
                    if(previewFragment!=null){
                        previewFragment.setData(bys,offset,length);
                    }
                }

                @Override
                public void onChannel(final int channel) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            currentchannel = channel;
                            channel_current.setText(currentchannel+"");
                            if(showText!=null){
                                showText.setText(currentchannel+"");
                            }
                        }
                    });

                }

                @Override
                public void onBattery(final int battery) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (battery > 80) {
                                battery_state_iv.setImageResource(BaseFinal.batteryIds[4]);
                            } else if (battery > 60) {
                                battery_state_iv.setImageResource(BaseFinal.batteryIds[3]);
                            } else if (battery > 40) {
                                battery_state_iv.setImageResource(BaseFinal.batteryIds[2]);
                            } else if (battery > 20) {
                                battery_state_iv.setImageResource(BaseFinal.batteryIds[1]);
                            } else {
                                battery_state_iv.setImageResource(BaseFinal.batteryIds[0]);
                                if(videoisStart){
                                    stopRecord();
                                    MyMethod.ShowDialog(context,R.string.battery_low);
                                }
                            }
                        }
                    });

                }

                @Override
                public void onRecordTime(final int time) {
                    if(videoisStart){
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                video_state.setText(MyMethod.getDateTimeByMillisecond(time*1000l/ServiceStatic.recordFps, "mm:ss"));
                            }
                        });
                    }
                }
            });
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    }

    private Handler handler = new Handler(Looper.getMainLooper());
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_uavpreview);
        context = UAVPreviewActivity.this;
        initView();
        initFragment();
        initService();
    }

    @Override
    protected void onResume() {
        super.onResume();
        isResume = true;
        bindService(usbIntent,usbConn,BIND_AUTO_CREATE);
        boolean[] values = MyMethod.getSelectItem(context, new String[]{"battery", "channel", "video", "capture"});
        if (values[0]) {
            battery_state_iv.setVisibility(View.VISIBLE);
        }
        if (values[1]) {
            channel_current.setVisibility(View.VISIBLE);
        }
        if (values[2]) {
            video_state.setVisibility(View.VISIBLE);
        }
        if (values[3]) {
            capture.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        isResume = false;
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (countDownTimer != null) {
            countDownTimer.cancel();
            countDownTimer = null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(usbService!=null){
            usbService.stopReceive();
        }
        unbindService(usbConn);
    }

    private void initView() {
        channel_current = findViewById(R.id.channel_current);
        capture = findViewById(R.id.capture);
        video_state = findViewById(R.id.video_state);
        battery_state = findViewById(R.id.battery_state);
        battery_state_iv = findViewById(R.id.battery_state_iv);
        lock_iv = findViewById(R.id.lock_iv);
        channel_current.setOnClickListener(this);
        capture.setOnClickListener(this);
        video_state.setOnClickListener(this);
        lock_iv.setOnClickListener(this);
        permissionRegister = new PermissionRegister(this);
        channelSelectPopup = new ChannelSelectPopup(new ChannelPopupCall() {
            @Override
            public void Select(String first, String second) {
                sendOrder(first, second);
            }

            @Override
            public void Search(TextView showView) {
                showText = showView;
                if(!isStartSearch){
                    isStartSearch=true;
                    sendOrder("0", "0");
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            isStartSearch=false;
                        }
                    },2000);
                }
            }
        });
        for (int i = 0; i < 9; i++) {
            strs[i] = i + 1 + "";
        }
    }

    private void sendOrder(String first, String second) {
        int x = Integer.parseInt(first) * 10 + Integer.parseInt(second);
        byte[] channel = new byte[11];
        channel[8] = 0;
        channel[9] = DProtocolType.D_FRAME_IWS_CHANNEL_SET & 0xff;
        channel[10] = (byte) (x & 0xff);
        DFrame.genDFrameHeader(channel, channel.length, DFrameEntity.DFRAME_ENTITY_MOBILE_DEVICE,
                DFrameEntity.DFRAME_ENTITY_IWT_GS, DFrameType.DFRAME_TYPE_DPROTOCOL,
                3);
        if (usbService != null) {
            BaseStatic.savaInfoToSD("send channel===" + x+"  发送信道");
            usbService.SendToUsb(channel, 0, 11);
        }
    }

    private void initFragment() {
        fragmentManager = getSupportFragmentManager();
        previewFragment = PreviewFragment.newInstance();
        selectFragment = SelectFragment.newInstance();
        fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.add(R.id.fl_control_fragments_content, previewFragment);
        fragmentTransaction.add(R.id.frame_layout, selectFragment);
        fragmentTransaction.hide(selectFragment);
        fragmentTransaction.commit();
    }

    private void initService() {
        usbIntent = new Intent(this,USBConnetService.class);
        usbConn = new UsbConn();
    }

    private void startCountDownTimer2() {
        if (countDownTimer != null) {
            countDownTimer.cancel();
            countDownTimer = null;
        }
        countDownTimer = new CountDownTimer(5000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
            }

            @Override
            public void onFinish() {
                if(isResume){
                    lock_iv.setVisibility(View.GONE);
                    selectHide();//倒计时隐藏
                }
            }
        };
        countDownTimer.start();
    }

    private void selectHide() {
        fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.hide(selectFragment);
        fragmentTransaction.commit();
        itemFragmentShow = false;
    }

    private void selectShow(){
        fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.show(selectFragment);
        fragmentTransaction.commit();
        itemFragmentShow = true;
    }

    @Override
    public void onClick(View v) {

        if (v == channel_current) {
            if (itemFragmentShow) {
                selectHide();//点击信道隐藏selectfragment
            } else {
                channelSelectPopup.setStrs(strs);
                channelSelectPopup.setChannel(currentchannel);
                channelSelectPopup.init(context);
            }

        } else if (v == capture) {
            if (itemFragmentShow) {
                selectHide();//点击截屏隐藏selectfragment
            } else {
                if (previewFragment != null) {
                    previewFragment.setCapture();
                }
            }

        } else if (v == video_state) {
            if (itemFragmentShow) {
                selectHide();//点击录像隐藏selectfragment
            } else {
                if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
                    permissionRegister.CheckPermission(WRITE_EXTERNAL_STORAGE,R.string.video_msg, 1,this);
                }else{
                    getVersion(VerFlag.MAIN);
                }
            }

        } else if (v == lock_iv) {
            if (isLock) {
                lock_iv.setImageResource(R.mipmap.unlock);
                isLock = false;
                if (!itemFragmentShow) {
                    selectShow();
                }
                startCountDownTimer2();
            } else {
                lock_iv.setImageResource(R.mipmap.lock);
                isLock = true;
                selectHide();//点击加锁隐藏selectfragment
            }

        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
    }

    @Override
    public void onFragmentInteraction(Uri uri) {

    }

    @Override
    public void onClick() {
        if (!isLock) {
            lock_iv.setVisibility(View.VISIBLE);
            if (!itemFragmentShow) {
                selectShow();
            }else{
                selectHide();
                lock_iv.setVisibility(View.GONE);
            }
            startCountDownTimer2();
        } else {
            lock_iv.setVisibility(View.VISIBLE);
            startCountDownTimer2();
        }
    }

    @Override
    public void StartReceive() {
        if(usbService!=null){
            usbService.startReceive();
        }
    }

    @Override
    public void onFragmentClick(CompoundButton buttonView, boolean isChecked) {
        int i = buttonView.getId();
        if (i == R.id.battery_cb) {
            if (isChecked) {
                battery_state_iv.setVisibility(View.VISIBLE);
                MyMethod.saveSelectItem(context, new String[]{"battery"}, new boolean[]{true});
            } else {
                battery_state_iv.setVisibility(View.GONE);
                MyMethod.saveSelectItem(context, new String[]{"battery"}, new boolean[]{false});
            }

        } else if (i == R.id.channel_cb) {
            if (isChecked) {
                channel_current.setVisibility(View.VISIBLE);
                MyMethod.saveSelectItem(context, new String[]{"channel"}, new boolean[]{true});
            } else {
                channel_current.setVisibility(View.GONE);
                MyMethod.saveSelectItem(context, new String[]{"channel"}, new boolean[]{false});
            }

        } else if (i == R.id.video_cb) {
            if (isChecked) {
                video_state.setVisibility(View.VISIBLE);
                MyMethod.saveSelectItem(context, new String[]{"video"}, new boolean[]{true});
            } else {
                video_state.setVisibility(View.GONE);
                MyMethod.saveSelectItem(context, new String[]{"video"}, new boolean[]{false});
            }

        } else if (i == R.id.jieping_cb) {
            if (isChecked) {
                capture.setVisibility(View.VISIBLE);
                MyMethod.saveSelectItem(context, new String[]{"capture"}, new boolean[]{true});
            } else {
                capture.setVisibility(View.GONE);
                MyMethod.saveSelectItem(context, new String[]{"capture"}, new boolean[]{false});
            }

        }
    }

    @Override
    public void ScanWifi() {

    }

    @Override
    public void startUsbPreview() {

    }

    @Override
    public void startPreview() {

    }

    @Override
    public void getVersion(VerFlag flag) {
        if (!videoisStart) {
            startRecord();
        } else {
            stopRecord();
        }
    }

    @Override
    public void Cancel() {

    }

    private long time;
    private Runnable run = new Runnable() {
        @Override
        public void run() {
            if (videoisStart) {
                long timestamp = System.currentTimeMillis() - time;
                String str1 = MyMethod.getDateTimeByMillisecond(timestamp, "mm:ss");
                video_state.setText(str1);
                handler.postDelayed(run, 1000);
            }
        }
    };

    private void startRecord(){
        video_state.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.mipmap.oval), null, null, null);
        time = System.currentTimeMillis();
        videoisStart = true;
        if(usbService!=null){
            usbService.startRecord();
        }
        video_state.setEnabled(false);
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                video_state.setEnabled(true);
            }
        },1000);
        ServiceStatic.videoisEnd = false;
        BaseStatic.videoisLaunch = true;
        BaseStatic.savaInfoToSD("startRecord");
    }

    private void stopRecord(){
        video_state.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.mipmap.video), null, null, null);
        video_state.setText(R.string.video);
        videoisStart = false;
        time = 0;
        if(usbService!=null){
            usbService.stopRecord();
        }
        video_state.setEnabled(false);
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                video_state.setEnabled(true);
            }
        },1000);
        ServiceStatic.videoisEnd = true;
        BaseStatic.savaInfoToSD("stopRecord");
    }
}
